﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace Wormhole.UI.Application.Dialogs.JoinGame
{
	/// <author>Hannes Foulds</author>
	/// <date>22 September 2008</date>
	/// <summary>
	/// Interaction logic for Connect.xaml
	/// </summary>
	public partial class Connect : Window
	{
		#region Properties

		#region Game
		/// <summary>
		/// The Game Engine object.
		/// </summary>
		public Engine.Game Game { get; set; }
		#endregion

		#region Connected
		/// <summary>
		/// Was a connection asstablished.
		/// </summary>
		protected bool Connected { get; set; }
		#endregion

		#region Server
		/// <summary>
		/// The address of the IRC server to connect to.
		/// </summary>
		public string Server
		{
			get { return this.txtServer.Text; }
			set { this.txtServer.Text = value; }
		}
		#endregion

		#region Port
		/// <summary>
		/// The IRC port the server is on.
		/// </summary>
		public int Port
		{
			get { return Convert.ToInt32(this.txtPort.Text); }
			set { this.txtPort.Text = value.ToString(); }
		}
		#endregion

		#region Player Name
		/// <summary>
		/// The player name.
		/// </summary>
		public string PlayerName
		{
			get { return this.txtPlayerName.Text; }
			set { this.txtPlayerName.Text = value; }
		}
		#endregion

		#endregion

		#region Constructor
		/// <summary>
		/// Initialize a default instance of the class.
		/// </summary>
		public Connect()
		{
			InitializeComponent();
			this.Connected = false;
		}
		#endregion

		#region Events

		#region Closing
		/// <summary>
		/// Handle the closing event.
		/// </summary>
		/// <param name="e">The cancel event arguments.</param>
		protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
		{
			if (!this.Connected)
				Application.App.Current.Shutdown();
		}
		#endregion

		#region Connect Click
		/// <summary>
		/// The event handler for the connect button
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btnConnect_Click(object sender, RoutedEventArgs e)
		{
			this.ConnectToServer();
		}
		#endregion

		#endregion
		
		#region Connect
		/// <summary>
		/// Attempt to connect to the game server.
		/// </summary>
		protected void ConnectToServer()
		{
			try
			{
				this.Game.Connect(this.Server, this.Port, this.PlayerName);
				this.Connected = true;
				this.Close();
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
			}
		}
		#endregion
	}
}
